using System.Collections.Concurrent;
using FastDevTemplate.Service.Interface.DTO;

namespace FastDevTemplate.Service;

public class TokenService
{
    public const int ExpirationTimeMinute = 60;
    private static readonly ConcurrentDictionary<string, UserTokenInfoDto> UserTokenMap = new();

    public static UserTokenInfoDto GenerateToken(UserLoginDto userLoginDto)
    {
        var token = Guid.NewGuid().ToString();
        return UserTokenMap[userLoginDto.ID.ToString()] = new UserTokenInfoDto
        {
            Token = token,
            UserLoginDto = userLoginDto
        };
    }

    public static UserTokenInfoDto? RemoveToken(Guid userId)
    {
        UserTokenMap.Remove(userId.ToString(), out var token);
        return token;
    }

    public static IQueryable<KeyValuePair<string, UserTokenInfoDto>> GetList()
    {
        return UserTokenMap.AsQueryable();
    }

    public static UserTokenInfoDto? TryGetToken(Guid userId)
    {
        if (userId == Guid.Empty)
            return null;
        if (UserTokenMap.ContainsKey(userId.ToString()) == false)
            return null;
        var tokenModel = UserTokenMap[userId.ToString()];
        if (tokenModel.IsExpirationByMinute(ExpirationTimeMinute))
        {
            UserTokenMap.Remove(userId.ToString(), out _);
            return null;
        }

        return tokenModel;
    }
}